package com.nulldev.util.VariableAPI;

import com.nulldev.util.VariableAPI.util.strings.codepoint.Internal;
import com.nulldev.util.VariableAPI.util.strings.codepoint.StringLatin1;
import com.nulldev.util.VariableAPI.util.strings.codepoint.StringUTF16;

public class CharUtils {

	public static boolean equals(final char[] left, final char[] right) {
		if (left == null || right == null)
			return false;
		if (left.length != right.length) {
			return false;
		}
		boolean result = true;
		for (int i = left.length - 1; i >= 0; i--) {
			result &= left[i] == right[i];
		}
		return result;
	}

	public static boolean contains(final char[] arr, final char chr) {
		if (arr == null)
			return false;
		if (arr.length == 0) {
			return false;
		}
		for (int i = arr.length - 1; i >= 0; i--) {
			if (arr[i] == chr)
				return true;
		}
		return false;
	}

	public static String toString(int codePoint) {
		return valueOfCodePoint(codePoint);
	}

	public static String toString(int[] codePoints) {
		final StringBuilder builder = new StringBuilder(codePoints.length);
		for (final int codePoint : codePoints)
			builder.append(valueOfCodePoint(codePoint));
		return builder.toString();
	}

	@SuppressWarnings("deprecation")
	static String valueOfCodePoint(int codePoint) {
		if (StringLatin1.canEncode(codePoint)) {
			return new String(StringLatin1.toBytes((char) codePoint), Internal.LATIN1);
		} else if (Character.isBmpCodePoint(codePoint)) {
			return new String(StringUTF16.toBytes((char) codePoint), Internal.UTF16);
		} else if (Character.isSupplementaryCodePoint(codePoint)) {
			return new String(StringUTF16.toBytesSupplementary(codePoint), Internal.UTF16);
		}

		throw new IllegalArgumentException(String.format("Not a valid Unicode code point: 0x%X", codePoint));
	}

	public static int[] asIntArray(final char[] arr) {
		final int[] output = new int[arr.length];
		for (int i = 0; i < arr.length; i++)
			output[i] = arr[i];
		return output;
	}
}
